#include <iostream>
using namespace std;

void ReplaceBlank(char [], int length);

int main(int argc, char * argv)
{
    char string[50] = "                ";
    cout << string << endl;
    ReplaceBlank(string, sizeof(string));
    cout << string << endl;
    return 0;
}

void ReplaceBlank(char string[], int length)
{
    if (string == NULL || length <= 0)
        return;
    // originalLength为字符串string的实际长度
    int originalLength = 0;
    int numOfBlank = 0;
    int i = 0;
    while (string[i] != '\0')
    {
        ++originalLength;
        if (string[i] == ' ')
            ++numOfBlank;
        ++i;
    }
    // newLength为把空格替换成'%20'之后的长度 
    int newLength = originalLength + 2 * numOfBlank;
    if (newLength > length)
        return;
    
    int idxOfOriginal = originalLength;
    int idxOfNew = newLength;

    while(idxOfOriginal >= 0 && idxOfNew > idxOfOriginal)
    {
        if(string[idxOfOriginal] == ' ')
        {
            string[idxOfNew--] = '0';
            string[idxOfNew--] = '2';
            string[idxOfNew--] = '%';
        }
        else
        {
            string[idxOfNew--] = string[idxOfOriginal];
        }
        --idxOfOriginal;
    }
}
